/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: LoginController
 * Author:   zmjha
 * Date:     2020/8/3 20:47
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zmj.controller;

import com.zmj.entity.User;
import com.zmj.service.UserService;
import com.zmj.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zmjha
 * @create 2020/8/3
 * @since 1.0.0
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /*注册*/
    @RequestMapping("/reg")
    public String res(User user, Model model) {
        user.setStatus(0);
        String code = UUIDUtils.getUUID() + UUIDUtils.getUUID();
        user.setCode(code);
        userService.register(user);
        model.addAttribute("msg", "注册成功前往邮箱激活！");
        return "login";
    }

    /**
     * 校验邮箱中的code激活账户
     * 首先根据激活码code查询用户，之后再把状态修改为"1"
     */
    @RequestMapping(value = "/checkCode")
    public String checkCode(String code) {
        User user = userService.checkCode(code);
        System.out.println(user);
        //如果用户不等于null，把用户状态修改status=1
        if (user != null) {
            user.setStatus(1);
            //把code验证码清空，已经不需要了
            user.setCode("");
            System.out.println(user);
            userService.updateUserStatus(user);
        }
        return "login";
    }

    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        if (user.getPassword() != null && user.getEmail() != null && user.getUsername() != null) {
            User token= userService.login(user);
            request.getSession().setAttribute("user",token);
            return "main";
        }else {
            return "login";
        }
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
}